import { getStorage, setStorage } from '../../bridge.js'
import Book from './book.js'

export default class Books {
  constructor({ container, navContainer }) {
    this.container = container
    this.navContainer = navContainer
  }

  async initBooks() {
    this.booksData = (await getStorage('books')) || []
    this.books = this.booksData.map((p) => {
      const book = new Book({ uuid: p.uuid, bookName: p.bookName, url: p.url })
      if (p.active) {
        this._renderBook(book)
      }
      return book
    })
    return this.booksData
  }

  async _renderBook(book) {
    if (book) {
      await book.render({ container: this.container })
      this.navContainer.innerHTML = book.renderNav()
    }
  }

  renderBook(index) {
    const book = this.books[index]
    return this._renderBook(book)
  }

  currentBook() {
    return this.books.find((p) => p.isActive())
  }

  exitCurrentBook() {
    const book = this.currentBook()
    if (book) {
      book.destroy()
    }
    this.save()
  }

  currentBookNextPage() {
    const book = this.currentBook()
    if (book) {
      book.nextPage()
    }
  }

  currentBookPrevPage() {
    const book = this.currentBook()
    if (book) {
      book.prevPage()
    }
  }

  currentBookGoPageByUrl(url) {
    const book = this.currentBook()
    if (book) {
      book.goPageByUrl(url)
    }
  }

  addAndRenderBook(url) {
    const book = new Book({ url })
    this.books.push(book)
    this.renderBook(this.books.length - 1).then(() => {
      this.save()
    })
    return book
  }

  openBook(uuid) {
    const book = this.books.find((p) => p.uuid === uuid)
    if (book) {
      this._renderBook(book)
    }
    this.save()
  }

  removeBook(uuid) {
    const index = this.books.findIndex((p) => p.uuid === uuid)
    const book = this.books.splice(index, 1)
    book.destroy()
  }

  save() {
    const booksData = this.books
      .map((p) => ({
        uuid: p.uuid,
        bookName: p.bookName,
        url: p.url,
        active: p.isActive(),
      }))
      .filter((p) => p.uuid)
    return setStorage('books', booksData)
  }
}
